<template>
    <div class="wrap">
        <div class="container">
            <div class="position_block">
                <div class="my_car_text">确认订单</div>
            </div>
            <div class="car_center_content">
                <div class="car_out_content">
                    <div class="xzqy">
                        <div class="qybt">选择企业<span v-if="allEnterpriseLoading == false && data.enterprise_list.length > 3" @click="allEnterprise">更多企业</span></div>
                        <ul class="qiye">
                            <li :class="item.checked ? 'active': ''" v-for="(item, index) in data.enterprise_list.slice(0, 3)" :key="index">
                                <i v-if="item.is_default == '1'">默认</i>
                                <span>{{ item.name }}</span>
                                <p>{{ item.address }}</p>
                            </li>
                            <div v-if="data.enterprise_list.length > 3 && allEnterpriseLoading">
                                <li :class="item.checked ? 'active': ''" v-for="(item, index) in data.enterprise_list.slice(3, data.enterprise_list.length)" :key="index">
                                    <i v-if="item.is_default == '1'">默认</i>
                                    <span>{{ item.name }}</span>
                                    <p>{{ item.address }}</p>
                                </li>
                            </div>
                        </ul>
                        <div class="fpxx">
                            <div class="fptitle">发票信息</div>
                            <ul class="fpnr">
                                <li>企业税号：{{ data.invoiceInfo.paragraph }}</li>
                                <li>开户银行：{{ data.invoiceInfo.bank_name }}</li>
                                <li>联系电话：{{ data.invoiceInfo.telephone }}</li>
                                <li>银行账户：{{ data.invoiceInfo.bank_card }}</li>
                            </ul>
                        </div>
                        <div class="fpdz">
                            <div class="fpdzbt">收票地址</div>
                            <div class="dzxz">
                                <el-select v-model="orderInfo.address_id" placeholder="请选择收票地址" popper-class="dzxz_elpopperbox">
                                    <el-option
                                        v-for="(item, index) in data.address_list"
                                        :key="index"
                                        :label="item.consignee + ' ' + item.phone + ' ' + item.postal_code + '  ' + item.province_name + '  ' + item.city_name + '  ' + item.county_name + '  ' + item.town_name + '  ' + item.address"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </div>

                    <div class="xzkdfs">
                        <div class="kdfsxx">选择快递方式</div>
                        <ul class="sfwl">
                            <li v-for="(item, index) in data.express_list" :key="index" :class="item.checked ? 'active' : '' " @click="changeExpress(item)">
                                <span>{{ item.title }}</span>
                            </li>
                        </ul>
                        <div class="sfbz">
                            <p> {{ data.express_list.find(x => x.checked) != null ? data.express_list.find(x => x.checked).value : "" }}</p>
                            <!-- <p>使用空运物流可能会产生额外费用。空运物流收费标准如下：</p>
                            <p>· 首重价：不同目的地的首重价格可能会有所差异，一般在15元-30元人民币之间。</p>
                            <p>· 首重价：不同目的地的首重价格可能会有所差异，一般在15元-30元人民币之间。</p>
                            <p>· 首重价：不同目的地的首重价格可能会有所差异，一般在15元-30元人民币之间。</p>
                            <p>· 首重价：不同目的地的首重价格可能会有所差异，一般在15元-30元人民币之间。</p> -->
                        </div>
                    </div>
                    <div class="shdzgs">
                        <div class="xzdz">选择收货地址
                            <div class="xzgddz">
                                <a v-if="isAddBut" class="addAddress" @click="openAddAddress">新增收货地址</a>
                                <span v-if="allAddressLoading == false"></span>
                                <a class="moreAddress" v-if="allAddressLoading == false" @click="allAddress">更多地址</a>
                            </div>
                        </div>
                        <ul class="dzxx">
                            <li :class="item.checked ? 'active' : '' " v-for="(item, index) in data.harvest_address_list.slice(0, 3)" :key="index" @click="changeAddress(item)">
                                <i>默认</i>
                                <span>{{ item.consignee }}   {{ item.phone }}</span>
                                <!-- <p>{{ item.province_name + item.city_name + item.county_name + item.town_name + item.address }}</p> -->
                                <p>{{ item.province_name + item.city_name + item.county_name + item.town_name + item.address }}</p>
                            </li>
                            <div v-if="data.harvest_address_list.length > 3 && allAddressLoading">
                                <li :class="item.checked ? 'active' : '' " v-for="(item, index) in data.harvest_address_list.slice(3, data.harvest_address_list.length)" :key="index" @click="changeAddress(item)">
                                    <i>默认</i>
                                    <span>{{ item.consignee }}   {{ item.phone }}</span>
                                    <p>{{ item.province_name + item.city_name + item.county_name + item.town_name + item.address  }}</p>
                                </li>
                            </div>
                        </ul>
                        <div class="ddgs" v-if="isProvinceDiv">
                            <div class="gstitle">选择订单归属</div>
                            <div class="gsdz">
                                <el-select v-model="orderInfo.province_id" placeholder="请选择所在省/直辖市" @change="changeProvince" popper-class="dzxz_elpopperbox">
                                    <el-option :label="item.province_name" :value="item.province_id" v-for="(item, index) in provinceList" :key="index"></el-option>
                                    <!-- <el-option label="区域二" value="beijing"></el-option> -->
                                </el-select>
                                <el-select v-model="orderInfo.city_id" ref="city" placeholder="请选择所在市" @change="changeCity" popper-class="dzxz_elpopperbox">
                                    <el-option :label="item.city_name" :value="item.city_id" v-for="(item, index) in cityList" :key="index"></el-option>
                                </el-select>
                                <el-select v-model="orderInfo.manager_id" ref="manager" placeholder="请选择销售经理" popper-class="dzxz_elpopperbox">
                                    <el-option :label="item.username" :value="item.id" v-for="(item, index) in managerList" :key="index"></el-option>
                                    <!-- <el-option label="区域一" value="shanghai"></el-option>
                                    <el-option label="区域二" value="beijing"></el-option> -->
                                </el-select>
                            </div>
                        </div>
                    </div>

                    <div class="qrcpxx">
                        <div class="qrcpbt">确认产品信息</div>
                    </div>
                    <div class="car_qrdd">
                        <div>商品信息</div>
                        <div>订单备注</div>
                        <div>生产厂家</div>
                        <div>单价</div>
                        <div>数量</div>
                        <div>小计</div>
                    </div>
                    <!-- 商品列表 -->
                    <div class="car_qrddlist" v-for="(item, index) in data.new_goods_list" :key="index">
                        <div class="carqrdd_goods_info">
                            <div class="goods_img">
                                <img :src="$commonImageUrl(item.goods_image)">
                            </div>
                            <div class="goodsqrdd_spec_info">
                                <div class="goodsqrdd_name">{{ item.goods_title }}</div>
                                <p>型号：{{ item.goods_models }}</p>
                                <p>规格：{{ item.sku_name }}</p>
                                <p>备注：{{ item.goods_remark }}</p>
                            </div>
                        </div>
                        <div class="colorqrdd_gray">
                            
                        </div>
                        <div class="colorqrdd_gray">
                            {{ item.factory_name }}
                        </div>
                        <div>￥{{ item.goods_price }}</div>
                        <div class="carqrdd_num_operate">{{ item.goods_num }}</div>
                        <div class="listqrdd_count_price">￥{{ item.pay_price }}</div>
                    </div>
                    <!-- 商品列表 结束-->
                    <div class="jstj">
                        <div class="zjr">{{ data.total_goods_num}} 件商品，总商品金额：<span>￥{{ data.total_goods_price }}</span></div>
                        <div class="yunfei">运费：<span>￥{{ data.dispatch_amount }}</span></div>
                    </div>

                    <div class="spje">
                        <div class="sfprice">实付总额：<span class="price-icon">￥</span><span class="price">{{ data.total_pay_price }}</span></div>
                        <div class="address">寄送至：{{ defaultAddress.province_name + defaultAddress.city_name + defaultAddress.county_name + defaultAddress.town_name + defaultAddress.address }}   收货人：{{ defaultAddress.consignee }}   {{ defaultAddress.phone }}</div>
                    </div>
                    <div class="tjorder"><a @click="submitOrder">提交订单</a></div>
                </div>
            </div>
        </div>
        <el-dialog
            title="新增收货地址"
            :close-on-click-modal="false"
            :visible.sync="dialogAddVisible"
            width="800px"
            top="6%">
            <div class="dialog-content add-address">
                <el-form ref="form"  :model="form" status-icon :show-message="false" label-width="150px" label-position="left">
                    <el-form-item label="收货人"  prop="consignee" required>
                        <el-input v-model="form.consignee" placeholder="请输入收货人姓名" class="input-ww"></el-input>
                    </el-form-item>
                    <el-form-item  label="手机号"  prop="phone" required>
                        <el-input placeholder="请输入手机号" v-model="form.phone" class="input-with-select input-ww" >
                            <el-select v-model="form.prefix" slot="prepend" placeholder="+86">
                                <el-option label="+86" value="+86"></el-option>
                            </el-select>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="邮政编码" prop="postal_code" required>
                        <el-input v-model="form.postal_code" placeholder="请输入邮政编码" class="input-ww"></el-input>
                    </el-form-item>
                    <div class="form-item-block">
                        <el-form-item label="所在地区" prop="province_id" required>
                            <el-select v-model="form.province_id" placeholder="省/直辖市" @change="ProvinceChangeHandler">
                                <el-option 
                                    v-for="(item,index) in provinceList"
                                    :key="index"
                                    :label="item.province_name" 
                                    :value="item.province_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="city_id" ref="city_id" label-width="10px" required>
                            <el-select v-model="form.city_id" placeholder="市" @change="CityChangeHandler">
                                <el-option 
                                    v-for="(item,index) in addAddressCityList"
                                    :key="index"
                                    :label="item.city_name" 
                                    :value="item.city_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="county_id" ref="county_id" required>
                            <el-select v-model="form.county_id" placeholder="区/县" @change="CountyChangeHandler">
                                <el-option 
                                    v-for="(item,index) in addAddressCountyList"
                                    :key="index"
                                    :label="item.county_name" 
                                    :value="item.county_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item prop="town_id" ref="town_id" label-width="10px" required>
                            <el-select v-model="form.town_id"  placeholder="乡镇/街道">
                                <el-option 
                                    v-for="(item,index) in addAddressTownList"
                                    :key="index"
                                    :label="item.town_name" 
                                    :value="item.town_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <el-form-item label="详细地址" required prop="address">
                        <el-input v-model="form.address" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <div class="checkbox">
                            <el-checkbox true-label="1" false-label="0" v-model="form.is_default"></el-checkbox>设置为默认地址
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button class="btn-main" @click="onSubmit" :loading="addLoading">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 右侧在线客服 -->
        
        <!-- 右侧在线客服 结束 -->
    </div>
</template>

<script>
import api from "@/api/order";
import commonApi from "@/api/common";
import userApi from "@/api/user";
import addressApi from "@/api/address";
import { validatePhone } from "@/utils/common";
import { getUser } from "@/utils/auth";
export default {
    data() {
        return {
            isProvinceDiv: false,
            isAddBut:false,
            loading: false, // 页面加载
            query: [], // 计算参数
            // 页面数据
            data: {
                address_list: [],
                dispatch_amount: 0,
                enterprise_list: [],
                express_list: [],
                invoiceInfo: [],
                new_goods_list: [],
                total_goods_num: 0,
                total_goods_price: 0,
                total_pay_price: "",
                harvest_address_list: []
            },
            orderInfo: {
                address_id: null,
                province_id: null,
                city_id: null,
                manager_id: null
            },
            defaultAddress: {},
            provinceList: [],
            cityList: [],
            managerList: [],
            allAddressLoading: false,
            allEnterpriseLoading: false,
            // 新增售货地址
            form: {
                prefix: "+86",
                province_id: null,
                city_id: null,
                county_id: null,
                town_id: null,
            },
            dialogAddVisible: false,
            addAddressCityList: [], // 市
            addAddressCountyList: [], // 区县
            addAddressTownList: [], // 街道
            addLoading: false
        };
    },
    methods: {
        // 提交订单
        submitOrder: function () {
            // 企业信息
            var enterprise = this.data.enterprise_list.find(x => x.checked);
            if (enterprise == null) {
                this.$message.error("请选择企业信息");
                return;
            }
            // 收票地址判断
            if (this.orderInfo.address_id == null) {
                this.$message.error("请选择收票地址");
                return;
            }
            // 快递方式信息
            var express = this.data.express_list.find(x => x.checked);
            if (express == null) {
                this.$message.error("请选择快递方式");
                return;
            }
            // 收货地址
            var address = this.data.harvest_address_list.find(x => x.checked);
            if (address == null) {
                this.$message.error("请选择收货地址");
                return;
            }
            // 选择订单归属
            if (getUser().type == 0 && this.orderInfo.manager_id == null) {
                this.$message.error("请选择订单归属");
                return;
            }
            var input = {
                goods_list: this.query.list,
                address_id: address.id,
                enterprise_id: enterprise.id,
                express_type: express.name,
                belong_province_id: this.orderInfo.province_id,
                belong_city_id: this.orderInfo.city_id,
                belong_manager: this.orderInfo.manager_id,
                remark: this.query.remark,
                invoice_address_id: this.orderInfo.address_id,
                dispatch_amount: this.data.dispatch_amount,
                cart_ids: this.query.cart_ids
            }
            this.loading = true;
            api.CreateOrder(input)
                .then((res) => {
                    this.loading = false;
                    this.$router.push({ path: '/agency/orderall' })
                    this.$message.success("订单生成成功");
                })
                .catch((err) => {
                    this.loading = false;
                })
        },
        // 所有地址
        allAddress: function () {
            this.allAddressLoading = true;
        },
        // 所有企业
        allEnterprise: function () {
            this.allEnterpriseLoading = true;
        },
        // 切换省份
        changeProvince: function (val) {
            var input = {
                id: val,
                type: "city"
            }
            this.orderInfo.city_id = null;
            this.orderInfo.manager_id = null;
            commonApi.GetAllProvinces(input)
                .then((res) => {
                    this.cityList = res.data;
                })
        },
        // 切换城市
        changeCity: function (val) {
            var input = {
                city_id: val
            }
            this.orderInfo.manager_id = null;
            userApi.GetUserList(input)
                .then((res) => {
                    this.managerList = res.data;
                })
        },
        // 切换收货地址
        changeAddress: function (item) {
            this.data.harvest_address_list.forEach(element => {
                element.checked = false;
            })
            item.checked = true;
            this.defaultAddress = item;
            this.$forceUpdate();
            this.countExpressAmount();
        },
        // 计算运费
        countExpressAmount: function () {
            var express = this.data.express_list.find(x => x.checked);
            var address = this.data.harvest_address_list.find(x => x.checked);
            var input = {
                goods_list: this.query.list,
                express_name: express.name,
                address_id: address.id
            }
            api.PerOrder(input)
                .then((res) => {
                    this.data.dispatch_amount = res.data.dispatch_amount;
                    this.data.total_pay_price = res.data.total_pay_price;
                })
                .catch((err) => {

                })
        },
        // 切换企业
        changeEnterprise: function (item) {
            this.data.enterprise_list.forEach(element => {
                element.checked = false;
            })
            item.checked = true;
            this.$forceUpdate();
        },
        // 切换快递方式
        changeExpress: function (item) {
            this.data.express_list.forEach(element => {
                element.checked = false;
            })
            item.checked = true;
            this.$forceUpdate();
            this.countExpressAmount();
        },
        // 加载订单
        LoadGoods: function () {
            this.loading = true;
            var input = {
                goods_list: this.query.list
            }
            api.PerOrder(input)
                .then((res) => {
                    // 处理企业
                    this.data.enterprise_list = [];
                    res.data.enterprise_list.forEach(element => {
                        element.checked = false;
                        if (element.is_default == "1") {
                            element.checked = true;
                        }
                        this.data.enterprise_list.push(element);
                    })
                    // 处理发票
                    this.data.invoiceInfo = res.data.invoiceInfo;
                    // 处理地址
                    this.data.address_list = [];
                    res.data.address_list.forEach(element => {
                        element.checked = false;
                        if (element.is_default == "1") {
                            element.checked = true;
                            this.defaultAddress = element;
                        }
                        this.data.address_list.push(element);
                    })
                    this.data.harvest_address_list = JSON.parse(JSON.stringify(this.data.address_list));
                    // 处理快递
                    this.data.express_list = [];
                    res.data.express_list.forEach((element, index) => {
                        element.checked = false;
                        if (index == 0) {
                            element.checked = true;
                        }
                        this.data.express_list.push(element);
                    })
                    // 处理商品
                    this.data.new_goods_list = res.data.new_goods_list;

                    // 处理金额
                    this.data.dispatch_amount = res.data.dispatch_amount; // 运费
                    this.data.total_goods_num = res.data.total_goods_num; // 商品个数
                    this.data.total_goods_price = res.data.total_goods_price; // 商品价钱
                    this.data.total_pay_price = res.data.total_pay_price; // 支付金额

                    this.loading = false;
                })
                .catch((err) => {
                    this.loading = false;
                })
        },
        // 加载省份数据
        LoadProvinceList: function () {
            var _this = this;
            commonApi.GetAllProvinces()
                .then((res) => {
                    _this.provinceList = res.data;
                })
        },
        // 打开新增地址弹框
        openAddAddress: function () {
            this.dialogAddVisible = true;
            if (this.$refs.form) {
                this.$refs.form.resetFields();
            }
        },
        // 加载城市数据
        LoadAllProvincesList: function (type, id) {
            var input = {
                type: type,
                id: id
            }
            commonApi.GetAllProvinces(input)
                .then((res) => {
                    if (type == "city") {
                        this.addAddressCityList = res.data;
                        this.addAddressCountyList = [];
                        this.addAddressTownList = [];
                        this.$refs.city_id.resetField();
                        this.$refs.county_id.resetField();
                    } else if(type == "county") {
                        this.addAddressCountyList = res.data;
                        this.addAddressTownList = [];
                        this.$refs.county_id.resetField();
                    } else if (type == "town") {
                        this.addAddressTownList = res.data;
                    }

                    this.$refs.town_id.resetField();
                })
        },
        // 切换省份
        ProvinceChangeHandler: function (val) {
            this.LoadAllProvincesList("city", val)
        },
        // 改变市
        CityChangeHandler: function (val) {
            this.LoadAllProvincesList("county", val)
        },
        // 改变区县
        CountyChangeHandler: function (val) {
            this.LoadAllProvincesList("town", val)
        },
        // 保存地址
        onSubmit: function () {
            this.$refs.form.validate((valid) => {
                this.addLoading = true;
                if (valid) {
                    if (!validatePhone(this.form.phone)) {
                        this.$message.error("请输入正确的手机号");
                        this.addLoading = false;
                        return;
                    }
                    addressApi.CreateOrUpdateAddress(this.form)
                        .then((res) => {
                            this.$message.success("新增地址成功");
                            res.data.checked = false;
                            if (res.data.is_default == "0") {
                                this.data.harvest_address_list.push(res.data);
                                this.data.address_list.push(res.data);
                            } else {
                                this.data.harvest_address_list.unshift(res.data);
                            }
                            this.dialogAddVisible = false;
                            this.addLoading = false;
                        })
                }
            })
        }
    },
    mounted: function () {
        if (getUser().type == 1) {
            this.isAddBut = false;
            this.isProvinceDiv = false;
        } else { 
            this.isAddBut = true;
            this.isProvinceDiv = true;
        }
        if (this.$route.query.goods == null) {
            this.$message.error("结算商品有误");
            this.$router.push({path: '/memberCenter/cart'})
        }
        this.query = JSON.parse(atob(this.$route.query.goods));
        this.LoadGoods();
        this.LoadProvinceList();
    }
};
</script>
<style>

.car_out_content .el-select .el-input__inner{color:#999999;height:0.6rem;background-color:#fff;border-radius:10px;}
.car_out_content .el-select .el-select-dropdown__item{ font-size: 0.16rem;}


</style>